package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.BaseException;
import com.sky.exception.CreateException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;


@RequiredArgsConstructor
@Slf4j
@Service
public class SetmealServiceImpl implements SetmealService {

    private final SetmealMapper setMealMapper;
    private final SetmealDishMapper setmealDishMapper;
    private final DishMapper dishMapper;

    @Transactional
    @Override
    public void create(SetmealDTO setmealDTO) {
        //属性校验
        check(setmealDTO);
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setMealMapper.insert(setmeal);
        //添加菜品关联
        insertSetmealDish(setmealDTO, setmeal);
    }

    @Override
    public PageResult readPageSetmeal(SetmealPageQueryDTO setmealPageQueryDTO) {
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());
        Page<SetmealVO> setmealVOPage = setMealMapper.selectList(setmealPageQueryDTO);
        return new PageResult(setmealVOPage.getTotal(), setmealVOPage.getResult());
    }

    @Transactional
    @Override
    public void deleteByIds(List<Long> ids) {
        //删除套餐 起售中的套餐不可以被删除
        Integer count = setMealMapper.selectCountByStatus(ids, StatusConstant.ENABLE);
        if (count > 0) {
            throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
        }
        setMealMapper.deleteByIds(ids);
        //删除套餐中的菜品
        setmealDishMapper.deleteBySetmealId(ids);
    }

    @Override
    public void status(Integer status, Long id) {
        //校验套餐中是否有未起售的菜品
        if (Objects.equals(status, StatusConstant.ENABLE)) {
            Integer count = dishMapper.selectCountByStatus(StatusConstant.DISABLE, id);
            if (count > 0) {
                throw new BaseException(MessageConstant.SETMEAL_ENABLE_FAILED);
            }
        }
        ArrayList<Long> ids = new ArrayList<>();
        ids.add(id);
        setMealMapper.updateStatus(status, ids);
    }

    @Override
    public SetmealVO infoById(Long id) {
        SetmealVO setmealVO = setMealMapper.selectById(id);
        List<SetmealDish> setmealDishes = setmealDishMapper.selectBySetmealId(id);
        setmealVO.setSetmealDishes(setmealDishes);
        return setmealVO;
    }

    @Transactional
    @Override
    public void updateById(SetmealDTO setmealDTO) {
        check(setmealDTO);
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        setMealMapper.updateById(setmeal);
        setmealDishMapper.deleteBySetmealId(Collections.singletonList(setmeal.getId()));
        insertSetmealDish(setmealDTO, setmeal);
    }

    /**
     * 条件查询
     * @param setmeal
     * @return
     */
    public List<Setmeal> list(Setmeal setmeal) {
        List<Setmeal> list = setMealMapper.list(setmeal);
        return list;
    }

    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    public List<DishItemVO> getDishItemById(Long id) {
        return setMealMapper.getDishItemBySetmealId(id);
    }


    /**
     *  添加套餐和菜品关联表
     */
    private void insertSetmealDish(SetmealDTO setmealDTO, Setmeal setmeal) {
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if (Objects.nonNull(setmealDishes) && !setmealDishes.isEmpty()) {
            setmealDishes.forEach(e -> e.setSetmealId(setmeal.getId()));
            setmealDishMapper.insert(setmealDishes);
            //判断是否有未起售的的菜品
            Integer count = dishMapper.selectCountByStatus(StatusConstant.DISABLE, setmeal.getId());
            if (count > 0) {
                List<Long> ids = new ArrayList<>();
                ids.add(setmeal.getId());
                setMealMapper.updateStatus(StatusConstant.DISABLE, ids);
            }
        }
    }

    /**
     * 属性校验
     */
    private void check(SetmealDTO setmealDTO) {
        //套餐名称 2-20汉字 字母大小 数字 唯一
        String name = setmealDTO.getName();
        if (Objects.isNull(name) || !name.matches("[\\u4E00-\\u9FFFa-zA-Z0-9]{2,20}")) {
            throw new CreateException(MessageConstant.SETMEAL_NAME_IS_ERROR);
        }
        Integer count = setMealMapper.selectCount(setmealDTO);
        if (count > 0) {
            throw new CreateException(MessageConstant.SETMEAL_NAME_IS_DUPLICATE);
        }
        //价格 1-8数字 小数点后2位小数
        BigDecimal price = setmealDTO.getPrice();
        if (Objects.isNull(price) || !price.toString().matches("^(?=\\d*\\.?\\d*$)\\d{1,8}(\\.\\d{1,2})?$")) {
            throw new CreateException(MessageConstant.SETMEAL_PRICE_FORMAT_ERROR);
        }
        //套餐描述
        String description = setmealDTO.getDescription();
        if (description.matches("^(?!.*(.).*\\1)[\\u4E00-\\u9FFFa-zA-Z0-9]{2,20}$")) {
            throw new CreateException(MessageConstant.SETMEAL_DESCRIPTION_ERROR);
        }
    }
}
